<template>
  <div>
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      custom-class="drawerClass"
      destroy-on-close
      size="90%"
    >
      <el-form class="form" ref="form" :model="entity" label-width="100px" :rules="rules" v-loading="loading">
        <div class="mask" v-if="title == '编辑订单'"></div>
        <el-row :gutter="20">
          <el-col v-for="item in formList" :key="item.Id" :span="8">
            <el-form-item :label="item.Key" :prop="item.Keys">
              <a-input disabled v-model="entity[item.Keys]" v-if="item.isFormTrue == 'false'"></a-input>
              <!-- @select="CompanyShipperSelect($event, item)" -->
              <CompanyShipper
                disabled
                v-if="item.isFormTrue == 'true' && item.Keys == 'CarrierId'"
                @select="CompanyShipperSelect($event, item)"
                v-model="entity[item.Keys]"
                :CompanyId="Company"
              >
              </CompanyShipper>
              <!-- :disabled="item.isAddTrue == 'false'" -->
              <CompanySearchSelect
                disabled
                v-if="item.isFormTrue == 'true' && item.Keys == 'Company'"
                :disabled="true"
                @select="CompanySelect($event, item)"
                v-model="entity[item.Keys]"
              />
              <!-- :disabled="item.isAddTrue == 'false'" -->
              <CustomerSearchSelect
                disabled
                v-if="item.isFormTrue == 'true' && item.Keys == 'CustomerName'"
                @select="CustomerSelect($event, item)"
                :CompanyId="Company"
                v-model="entity[item.Keys]"
              />
              <ContactPersonSearhSelect
                disabled
                v-if="item.isFormTrue == 'true' && item.Keys == 'ContactPersonId'"
                :CompanyId="Company"
                :cCusCode="entity.CustomerId"
                v-model="entity[item.Keys]"
                @select="ContactPersonSelect($event, item)"
              />
              <!-- :disabled="item.isAddTrue == 'false'" -->
              <el-date-picker
                disabled
                v-if="item.type == 6 && item.isFormTrue == 'true'"
                style="width: 100%"
                v-model="entity[item.Keys]"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-for="(item, index) in tableDataList" :key="item.Id">
        <h2
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            margin: 0;
            padding: 0 8px 8px 8px;
          "
        >
          <span>货品信息</span>
          <!-- <a-button icon="el-icon-plus" type="primary" @click="handleAdd(index)"
          >新增</a-button
        > -->
        </h2>
        <div style="display: flex">
          <div style="width: 47%">
            <el-table
              :data="item.datalist"
              style="width: 100%"
              :max-height="600"
              v-loading="loading"
              highlight-selection-row
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" v-if="title === '拆分货单'"> </el-table-column>
              <el-table-column
                v-for="(im, ix) in item.columns"
                :key="im.dataIndex"
                :prop="im.dataIndex"
                :label="im.title"
                v-if="im.dataIndex != 'nums'"
              >
                <template slot-scope="scope">
                  <div v-if="im.dataIndex == 'Number'">{{ scope.$index + 1 }}</div>
                  <span
                    v-else
                    disabled
                    :type="im.type ? im.type : 'text'"
                    :max-length="im.maxlength ? im.maxlength : 200"
                    @input="im.actionCol == '1' ? handleChange(scope.row, im, scope.$index, ix) : () => {}"
                    >{{ scope.row[im.dataIndex] }}</span
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div
            style="
              width: 6%;
              border-left: 1px solid #ccc;
              border-right: 1px solid #ccc;
              display: flex;
              flex-direction: column;
              justify-content: space-around;
              align-items: center;
            "
          >
            <a-button @click="handleSplitLeft" icon="left"></a-button>
            <a-button @click="handleSplitRight" icon="right"></a-button>
          </div>
          <div style="width: 47%">
            <el-table
              :data="datalist1"
              style="width: 100%"
              :max-height="600"
              v-loading="loading"
              highlight-selection-row
              @selection-change="handleSelectionChangeSplit"
            >
              <el-table-column type="selection" width="55" v-if="title === '拆分货单'"> </el-table-column>
              <el-table-column
                v-for="(im, ix) in item.columns"
                :key="im.dataIndex"
                :prop="im.dataIndex"
                :label="im.title"
                v-if="im.dataIndex != 'nums'"
              >
                <template slot-scope="scope">
                  <div v-if="im.dataIndex == 'Number'">{{ scope.$index + 1 }}</div>
                  <span
                    v-else
                    disabled
                    :type="im.type ? im.type : 'text'"
                    :max-length="im.maxlength ? im.maxlength : 200"
                    @input="im.actionCol == '1' ? handleChange(scope.row, im, scope.$index, ix) : () => {}"
                    >{{ scope.row[im.dataIndex] }}</span
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div style="height: 50px"></div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '5px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1005,
        }"
      >
        <a-button @click="drawer = false" style="margin-right: 10px">取消</a-button>
        <a-button type="primary" :loading="btnLoading" @click="handleSubmit">保存</a-button>
      </div>

      <GoodsInfoSelect ref="goodsInfoSelect" @select="GoodsSelect" />
    </el-drawer>
    <!-- <el-dialog title="批量改价" :visible.sync="revampVisible" width="300px" :modal-append-to-body="false">
      <div>
        <span>加成率：</span>
        <a-input-number v-model="addrateValue"></a-input-number>%
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="revampVisible = false">取 消</el-button>
        <el-button type="primary" @click="revampOk">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import moment from 'moment'
import { toThousands } from '@/utils/Tools'
import GoodsInfoSelect from '@/components/components/GoodsInfoSelect.vue'
import CompanySearchSelect from '@/components/components/CompanySearchSelect.vue'
import CompanyShipper from '@/components/components/CompanyShipper.vue'
import CustomerSearchSelect from '@/components/components/CustomerSearchSelect.vue'
import ContactPersonSearhSelect from '@/components/components/ContactPersonSearhSelect.vue'
export default {
  components: {
    CompanySearchSelect,
    CustomerSearchSelect,
    ContactPersonSearhSelect,
    GoodsInfoSelect,
    CompanyShipper,
  },
  props: {
    parentObj: { type: Object },
  },
  // 是由于有的货单校验有的货单不校验 暂时先删除 后续根据需求追加
  // computed: {
  //   rules() {
  //     // var obj = {}

  //     // this.formList.forEach((item) => {
  //     //   if (item.isrules) {
  //     //     obj[item.Keys] = [{ required: true, message: `请填写${item.Key}` }]
  //     //   }
  //     // })
  //     // return obj
  //   },
  // },
  data() {
    return {
      revampVisibleLoading: false,
      revampVisible: false,
      revamList: [],
      drawer: false,
      direction: 'rtl',
      entity: {},
      rules: {},
      // rules: {
      //   CompanyName: [{ required: true, message: '请选择公司' }],
      //   CustomerName: [{ required: true, message: '请选择客户' }],
      //   BillId: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
      // },
      btnLoading: false,
      title: '',
      loading: false,
      timeout: null,
      tableDataList: [], // 表格组
      toThousands,
      formList: [], // 表单组
      tableIndex: 0, // 操作表格下标
      jsoncontent: {},
      Company: '',
      dataArrIndex: 0,
      addrateValue: '100',
      datalist1: [],
      revamListSplit: [],
      row: {},
    }
  },
  methods: {
    //拆单
    handleSplitLeft() {
      if (this.revamListSplit.length <= 0) {
        this.$message.info('请选择先单据')
        return
      }
      this.tableDataList[this.tableIndex].datalist.push(...this.revamListSplit)
      let arr = JSON.parse(JSON.stringify(this.datalist1))
      this.datalist1.forEach((item, index) => {
        this.revamListSplit.forEach((ite) => {
          if (item == ite) {
            delete arr[index]
          }
        })
      })
      this.datalist1 = arr.filter((item) => item)
    },
    handleSplitRight() {
      if (this.revamList.length <= 0) {
        this.$message.info('请选择先单据')
        return
      }
      this.datalist1.push(...this.revamList)
      let arr = JSON.parse(JSON.stringify(this.tableDataList[this.tableIndex].datalist))
      this.tableDataList[this.tableIndex].datalist.forEach((item, index) => {
        this.revamList.forEach((ite) => {
          if (item == ite) {
            delete arr[index]
          }
        })
      })
      this.tableDataList[this.tableIndex].datalist = arr.filter((item) => item)
    },
    handleSelectionChange(row) {
      console.log(row)
      this.revamList = row
    },
    handleSelectionChangeSplit(row) {
      console.log(row)
      this.revamListSplit = row
    },
    openRevamp() {
      console.log('111111111111')
      if (!this.revamList.length) {
        return this.$message.warning('请先选择行')
      }
      this.addrateValue = '100'
      this.revampVisible = true
    },
    revampOk() {
      if (!this.addrateValue) {
        return this.$message.error('请输入正确加成率')
      }
      this.loading = true
      const num = this.addrateValue / 100
      console.log(num)
      this.revamList.forEach((item) => {
        item.iInvRCost = Number(Number(item.iInvRCost) * num)
        item.SumiInvRCost = Number(item.iInvRCost) * Number(item.Quantity)
        item.SumiInvRCost = item.SumiInvRCost.toFixed(2)
      })
      this.revampVisible = false
      this.loading = false
      this.$message.success('已修改')
    },
    // 承运方选择
    CompanyShipperSelect(row, item) {
      this.entity.CarrierName = row.CarrierName
      // this.entity.Company = row.Id
      item.value = row.CarrierName
    },
    // 货品行件数变更
    handleChange(row, im, index, pIndex) {
      console.log()
      // num:当前输入值;row:当前行;im:列数据
      let actionNum = 0
      // 顺序依次 + - * /
      if (im.actionC == 0) {
        actionNum = Number(row[im.actionA]) + Number(row[im.actionB])
      } else if (im.actionC == 1) {
        actionNum = Number(row[im.actionA]) - Number(row[im.actionB])
      } else if (im.actionC == 2) {
        actionNum = Number(row[im.actionA]) * Number(row[im.actionB])
      } else actionNum = Number(row[im.actionA]) / Number(row[im.actionB])

      // 赋值
      row[im.actionD] = isNaN(actionNum) ? '' : actionNum.toFixed(2)
    },
    // 货品选择
    GoodsSelect(rows) {
      let flag = false
      rows.forEach((item) => {
        // 判断操作表格列是否已有该货品
        if (this.tableDataList[this.tableIndex].datalist.findIndex((im) => im.Id == item.Id) == -1) {
          this.dataArrIndex++
          this.tableDataList[this.tableIndex].datalist.unshift({
            ...JSON.parse(JSON.stringify(item)),
            Time: moment(new Date()).format('YYYY-MM-DD'),
          })
        } else {
          flag = true
        }
      })
      if (flag) {
        this.$message.warning('相同货品已过滤')
      } else {
        this.tableDataList[this.tableIndex].datalist.splice(this.dataArrIndex, 1)
      }
    },
    // 表格新增
    // handleAdd(index) {
    //   if (!this.entity.CustomerId) return this.$message.error("请选择收货方");
    //   this.tableIndex = index;
    //   this.$refs.goodsInfoSelect.openForm(this.entity.CustomerId, this.Company);
    // },
    handleAdd(index) {
      this.tableDataList[index].datalist.unshift({})
    },
    // 表格行点击
    handleWrit(index, scope) {
      if (!this.entity.CustomerId) return this.$message.error('请选择收货方')
      this.tableIndex = index
      this.dataArrIndex = scope.$index
      this.$refs.goodsInfoSelect.openForm(this.entity.CustomerId, this.Company)
    },
    // 表格行删除
    handleDelete(scope, index) {
      console.log(scope, index)
      this.tableDataList[index].datalist.splice(scope.$index, 1)
      this.$message.success('操作成功')
    },
    handleCopy(scope, index) {
      const copyO = JSON.stringify(this.tableDataList[index].datalist[scope.$index])
      this.tableDataList[index].datalist.splice(scope.$index, 0, JSON.parse(copyO))
    },
    // 公司选择 销售方
    CompanySelect(row, item) {
      this.entity.Sender = row.Title
      // this.entity.Company = row.Id
      item.value = row.Title
      // this.entity.CompanyName = row.Title;
      // this.$refs.form.clearValidate("CompanyName");
    },
    // 客户选择
    CustomerSelect(row, item) {
      this.$set(this.entity, 'Customer', row.cCusName)
      this.$set(this.entity, 'CustomerId', row.Id)
      this.$set(this.entity, 'Addres', row.cCusAddress)
      item.value = row.cCusName

      // this.$refs.form.clearValidate("CustomerName");
    },
    // 签收人选择
    ContactPersonSelect(row, item) {
      this.entity.ContactPersonName = row.cName
      this.entity.ContactPersonId = row.Id
      this.entity.CustomerPhone = row.cPhone
      item.value = row.cName

      this.$refs.form.clearValidate('ContactPerson')
    },
    init() {
      this.entity = {}
      this.drawer = true
      this.formList = []
      this.tableDataList = []
      this.datalist1 = []
      // if (this.$refs['form']) {
      //   this.$refs['form'][0].resetField()
      // }
    },
    openForm(content, mode, Company, TemName, row) {
      this.row = row
      console.log(Company)
      this.init()
      this.Company = Company
      if (mode) {
        this.title = '拆分货单'
        this.entity = content
        var arr = JSON.parse(content.Content).printlist
        this.jsoncontent = { ...JSON.parse(content.Content) }
        this.$httpp
          .post(`/Base/Base_Template/GetCompanyTemp?CompayId=${this.parentObj.queryParam.SupplieId}`)
          .then((res) => {
            this.newBillContent = { ...JSON.parse(res.Data.Content) }
          })
        var arr2 = arr.filter((item) => {
          return !item.ispringt
        })
        arr2.sort((a, b) => a.index - b.index)
        arr2.forEach((item) => {
          console.log(item.ispringt)
          this.$set(this.entity, item.Keys, item.value)
        })
        this.formList = arr2
        this.tableDataList = arr.filter((item) => {
          return item.type === '4'
        })
      } else {
        this.title = '新增货单'
        var arr = JSON.parse(content).printlist
        this.jsoncontent = { ...JSON.parse(content) }
        var arr2 = arr.filter((item) => {
          return !item.ispringt
        })
        arr2.sort((a, b) => a.index - b.index)
        arr2.forEach((item) => {
          if (item.Keys === 'Company') {
            this.$set(item, 'value', TemName)
            this.$set(this.entity, 'Company', Company)
          } else {
            this.$set(item, 'value', '')
          }
        })
        console.log(arr2, '123456')
        this.formList = arr2

        this.tableDataList = arr.filter((item) => {
          return item.type === '4'
        })
        this.tableDataList.forEach((item) => {
          item.datalist = []
        })
        console.log(arr2)
        // 获取公司发货地址
        this.$httpp.post('/Base_Manage/Base_Company/GetCommadders?compayid=' + Company).then((res) => {
          if (res.Success && res.Data.length > 0) {
            this.$set(this.entity, 'gongsiaddress', res.Data[0])
          }
        })
        this.$set(this.entity, 'BillId', new Date().getTime())
      }
    },
    handleClose(done) {
      done()
    },
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        if (this.tableDataList[0].datalist.length <= 0 || this.datalist1.length <= 0) {
          this.$message.error('货品信息任何一侧不能为空!')
          return
        }
        if (this.tableDataList.length > 0) {
          var arr = []
          this.tableDataList.forEach((item) => {
            console.log(item)
            if (item.datalist.length == 0) {
              arr.push(item)
            } else {
              // 检测需要合并项
              const newarr = item.datalist.reduce((pre, cur) => {
                const idx = pre.findIndex((im) => im.Id && cur.Id && im.Id == cur.Id && im.Batch == cur.Batch)
                // 非重复项加入  重复项件数相加
                if (idx == -1) {
                  pre.push(cur)
                } else {
                  pre[idx].Quantity = Number(pre[idx].Quantity) + Number(cur.Quantity)
                }
                return pre
              }, [])
              item.datalist = newarr
            }
          })

          if (arr.length > 0) {
            return this.$message.error('请添加货品信息!')
          }
        }
        var obj = { ...this.entity }
        // console.log("<<<<<<<<<<"+JSON.stringify(obj))
        this.formList.forEach((item) => {
          // if (!item.value) {
          //   item.value = obj[item.Keys]
          // }
          item.value = obj[item.Keys]
        })
        let numflag = false
        this.tableDataList.forEach((item) => {
          console.log(item, 'item')
          item.datalist.forEach((im, ix) => {
            console.log(im, 'im')
            im.Number = ix + 1
            if (!im.Quantity || im.Quantity <= 0) {
              numflag = true
            }
            im.cCusName = this.entity.Customer || ''
            if (!im.StatisticalQuantity) im.StatisticalQuantity = 0 // 数量
            if (!im.StatisticalWeight) im.StatisticalWeight = 0 // 重量
            if (!im.StatisticalPrice) im.StatisticalPrice = 0 // 价格
            // 所有件数相加
            im.StatisticalQuantity = isNaN(Number(im.Quantity)) ? 0 : Number(im.Quantity)
            // 件数乘单重相加
            im.StatisticalWeight =
              (isNaN(Number(im.Quantity)) ? 0 : Number(im.Quantity)) *
              (isNaN(Number(im.Weight)) ? 0 : Number(im.Weight))
            // 件数乘单价相加
            im.StatisticalPrice =
              (isNaN(Number(im.Quantity)) ? 0 : Number(im.Quantity)) *
              (isNaN(Number(im.iInvRCost)) ? 0 : Number(im.iInvRCost))

            if (!im.InventoryPrice) {
              this.$set(im, 'InventoryPrice', im.SumiInvRCost)
            }
          })
        })

        if (numflag) {
          return this.$message.error('货品信息中存在未填写或小于零的数量')
        }
        // JSON表单
        this.jsoncontent.printlist.forEach((item) => {
          this.formList.forEach((val) => {
            // console.log(val, item);
            if (item.Id === val.Id) {
              item.value = val.value
            }
          })
          if (item.Id === '5') {
            item.datalist = this.tableDataList[0].datalist
          }
          // this.tableDataList.forEach((val2) => {
          //   if (item.Id === val2.Id) {
          //     item.value = val2.value
          //     item.datalist = val2.datalist
          //     item.columns = val2.columns
          //   }
          // })
        })
        this.newBillContent.printlist.forEach((item) => {
          this.formList.forEach((val) => {
            // console.log(val, item);
            if (item.Id === val.Id) {
              item.value = val.value
            }
          })
          if (item.Id === '5') {
            item.datalist = this.datalist1
          }
          // this.tableDataList.forEach((val2) => {
          //   if (item.Id === val2.Id) {
          //     item.value = val2.value
          //     item.datalist = val2.datalist
          //     item.columns = val2.columns
          //   }
          // })
        })
        const isRemark = this.tableDataList[0].datalist.some((item) => {
          return item.Remark
        })
        // console.log("<<<<<<<<<<<<<<"+isRemark)
        this.jsoncontent.isRemark = isRemark

        this.entity.content = JSON.stringify(this.jsoncontent)
        // 主表内容
        this.entity.IP = sessionStorage.getItem('ip')
        this.entity.Company = '1714814800086700032'
        let url = ''
        if (this.title == '拆分货单') {
          url = '/BO/BillList/SplitBillBill'
          // this.entity.Status = -1;
        } else {
          url = '/BO/BillList/SaveData'
          this.entity.Status = 0
        }
        this.btnLoading = true
        this.loading = true
        console.log({
          data: this.entity,
          datalist: this.tableDataList[0].datalist,
        })
        this.entity.DomainName = 'hzq'
        this.entity.MadeDate = this.row.MadeDate
        // 表单保存
        this.$httpp
          .post(url, {
            data: this.entity,
            newBillContent: JSON.stringify(this.newBillContent),
            datalist: this.tableDataList[0].datalist,
            datalist1: this.datalist1,
          })
          .then((res) => {
            this.loading = false
            this.btnLoading = false
            if (res.Success) {
              this.$message.success('操作成功')
              if (this.title == '编辑货单') {
                this.drawer = false
                // this.parentObj.getFormData()
              } else {
                this.parentObj.getDataList()
                this.parentObj.queryParam.SupplieId = this.Company
              }

              this.drawer = false
            } else {
              this.$message.error(res.Msg)
            }
          })
      })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-drawer__body {
  padding: 0px 10px;
}

.iconStyle {
  color: #409eff;
}

.form {
  position: relative;
  padding-right: 10px;

  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 10;
    // background: #00000010;
  }
}

.warnBtn {
  color: red;
  margin-left: 8px;
}
</style>
